#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:app.py
# author:张世航
# datetime:2024/12/22 15:48
# software: PyCharm
"""
this is function  description 
"""
# import module your need

from flask import Flask, render_template, request, redirect, url_for
from models import db, Student

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:158158@localhost/python_test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

@app.route('/')
def index():
    students = Student.query.all()
    return render_template('index.html', students=students)

@app.route('/add_student', methods=['GET', 'POST'])
def add_student():
    # 处理添加学生的逻辑
    sno = request.form['Sno']
    sname = request.form['Sname']
    ssex = request.form['Ssex']
    sage = request.form['Sage']
    dno = request.form['Dno']
    sclass = request.form['Sclass']
    address = request.form['address']

    # 添加学生到数据库的逻辑
    new_student = Student(Sno=sno, Sname=sname, Ssex=ssex, Sage=sage, Dno=dno, Sclass=sclass, address=address)
    db.session.add(new_student)
    db.session.commit()

    return redirect(url_for('index'))

@app.route('/edit_student/<sno>', methods=['POST'])
def edit_student(sno):
    print(f"Editing student with Sno: {sno}")  # 调试输出
    student = Student.query.get(sno)
    if student:
        student.Sname = request.form['Sname']
        student.Ssex = request.form['Ssex']
        student.Sage = request.form['Sage']
        student.Dno = request.form['Dno']
        student.Sclass = request.form['Sclass']
        student.address = request.form['address']

        db.session.commit()
    else:
        print("Student not found")  # 调试输出
    return redirect(url_for('index'))

@app.route('/delete_student/<sno>', methods=['POST'])
def delete_student(sno):
    student = Student.query.get(sno)
    db.session.delete(student)
    db.session.commit()
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)
